package com.platform.lxh.netty.handler;

import com.alibaba.fastjson.JSONObject;
import com.platform.lxh.netty.model.*;
import com.platform.lxh.netty.resolve.*;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

/**
 * @create: 2021-03-10 20:07
 * @author: xiaoh.luo001@bkjk.com
 * @description:
 **/
public class ServerMessageHandler extends SimpleChannelInboundHandler<String> {

    private MessageResolverFactory resolverFactory = new MessageResolverFactory();

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        System.out.println("连接成功。。。");
        ctx.channel();
    }

    @Override
    public void channelRead0(ChannelHandlerContext ctx, String obj) throws Exception {

        Message message = JSONObject.parseObject(obj, Message.class);
        // 获取消息处理器
        Resolver resolver = resolverFactory.getMessageResolver(message);
        // 对消息进行处理并获取响应数据
        Message result = resolver.resolve(message);
        // 将响应数据写入到处理器中
        ctx.writeAndFlush(JSONObject.toJSONString(result));
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        // 注册request消息处理器
        resolverFactory.registerResolver(new RequestMessageResolver());
        // 注册response消息处理器
        resolverFactory.registerResolver(new ResponseMessageResolver());
        // 注册ping消息处理器
        resolverFactory.registerResolver(new PingMessageResolver());
        // 注册pong消息处理器
        resolverFactory.registerResolver(new PongMessageResolver());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}
